'use client'

import { useState } from 'react'
import {
  Modal,
  ModalOverlay,
  ModalContent,
  ModalHeader,
  ModalFooter,
  ModalBody,
  ModalCloseButton,
  Button,
  FormControl,
  FormLabel,
  Input,
  NumberInput,
  NumberInputField,
  NumberInputStepper,
  NumberIncrementStepper,
  NumberDecrementStepper,
  FormErrorMessage,
  VStack
} from '@chakra-ui/react'

interface NewChapterModalProps {
  isOpen: boolean;
  onClose: () => void;
  projectId: string;
  onCreateChapter: (projectId: string, title: string, order: number) => void;
  lastChapterNumber?: number;
}

export const NewChapterModal = ({ 
  isOpen, 
  onClose, 
  projectId,
  onCreateChapter,
  lastChapterNumber = 0
}: NewChapterModalProps) => {
  const [title, setTitle] = useState('')
  const [order, setOrder] = useState(lastChapterNumber + 1)
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [errors, setErrors] = useState<{title?: string}>({})
  
  const handleSubmit = () => {
    // 验证表单
    const newErrors: {title?: string} = {}
    if (!title.trim()) {
      newErrors.title = '章节标题不能为空'
    }
    
    if (Object.keys(newErrors).length > 0) {
      setErrors(newErrors)
      return
    }
    
    setIsSubmitting(true)
    
    // 创建新章节
    onCreateChapter(projectId, title, order)
    
    // 重置表单并关闭
    setTitle('')
    setOrder(lastChapterNumber + 1)
    setErrors({})
    setIsSubmitting(false)
    onClose()
  }
  
  return (
    <Modal isOpen={isOpen} onClose={onClose} size="md">
      <ModalOverlay />
      <ModalContent>
        <ModalHeader>创建新章节</ModalHeader>
        <ModalCloseButton />
        
        <ModalBody>
          <VStack spacing={4}>
            <FormControl isRequired isInvalid={!!errors.title}>
              <FormLabel>章节标题</FormLabel>
              <Input 
                value={title}
                onChange={(e) => setTitle(e.target.value)}
                placeholder="请输入章节标题"
              />
              {errors.title && (
                <FormErrorMessage>{errors.title}</FormErrorMessage>
              )}
            </FormControl>
            
            <FormControl>
              <FormLabel>章节序号</FormLabel>
              <NumberInput 
                value={order} 
                min={1}
                onChange={(_, val) => setOrder(val)}
              >
                <NumberInputField />
                <NumberInputStepper>
                  <NumberIncrementStepper />
                  <NumberDecrementStepper />
                </NumberInputStepper>
              </NumberInput>
            </FormControl>
          </VStack>
        </ModalBody>
        
        <ModalFooter>
          <Button variant="outline" mr={3} onClick={onClose}>
            取消
          </Button>
          <Button 
            colorScheme="red" 
            onClick={handleSubmit}
            isLoading={isSubmitting}
          >
            创建章节
          </Button>
        </ModalFooter>
      </ModalContent>
    </Modal>
  )
}
